//
//  RefuseRefundVC.m
//  yunbaolive
//
//  Created by ybRRR on 2020/2/20.
//  Copyright © 2020 cat. All rights reserved.
//

#import "RefuseRefundVC.h"

@interface RefuseRefundVC ()<UIPickerViewDelegate,UIPickerViewDataSource,UITextViewDelegate>
{
    UILabel *reasonLb;
    UIView *reasonPickBack;
    UIView *titleBack;
    UIPickerView *reasonPicker;
    NSArray *reasonArr;
    
    NSInteger selRow;
    NSString *selReasonStr;

    NSString *resonID;
    
    NSDictionary *selResonDic;
}
@property(nonatomic,strong)MyTextView  *reasonTextView;
@property(nonatomic,strong)UIView *textBackView;
@property(nonatomic,strong) UILabel *wordsNumL;                 //字符统计

@end

@implementation RefuseRefundVC

-(void)initData{
    reasonArr = [NSArray array];//@[@"买家未举证/举证无效",@"收到退货后再退款",@"已发货，买家运输"];
    selResonDic = [NSDictionary dictionary];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    self.subNavi.backgroundColor = UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
    self.naviLine.hidden = NO;
    self.naviLine.backgroundColor = RGB(245, 245, 245);

    self.titleL.text = YZMsg(@"拒绝退款");
    selReasonStr = @"";
    [self initData];
    
    titleBack= [[UIView alloc]init];
    titleBack.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:titleBack];
    [titleBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.equalTo(self.view);
        make.top.mas_equalTo(64+statusbarHeight);
        make.height.mas_equalTo(50);
    }];
    
    UILabel *titlelb = [[UILabel alloc]init];
    titlelb.font = [UIFont systemFontOfSize:14];
    titlelb.text = YZMsg(@"拒绝原因");
    titlelb.textColor = UIColor.blackColor;
    [titleBack addSubview:titlelb];
    [titlelb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleBack).offset(12);
        make.centerY.equalTo(titleBack);
        make.height.mas_equalTo(20);
    }];
    
    UIImageView *rightImg = [[UIImageView alloc]init];
    rightImg.image = [UIImage imageNamed:@"shop_right"];
    [titleBack addSubview:rightImg];
    [rightImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-10);
        make.width.height.mas_equalTo(16);
        make.centerY.equalTo(titleBack);
    }];
    
    reasonLb = [[UILabel alloc]init];
    reasonLb.textColor = Normal_TextColor;
    reasonLb.font = [UIFont systemFontOfSize:14];
    reasonLb.text = YZMsg(@"请选择");
    [titleBack addSubview:reasonLb];
    [reasonLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(rightImg.mas_left);
        make.centerY.equalTo(titleBack);
        make.height.mas_equalTo(20);
        make.left.greaterThanOrEqualTo(titlelb.mas_right).offset(2);
    }];
    
    UITapGestureRecognizer *reasonTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(reasonSelClick)];
    [titleBack addGestureRecognizer:reasonTap];
    
    [self.view layoutSubviews];
    [self.view addSubview:self.textBackView];
    
    UIButton *upBtn = [UIButton buttonWithType:0];
    upBtn.frame = CGRectMake(0, _window_height-40-ShowDiff, _window_width, 40);
    [upBtn setBackgroundColor:Pink_Cor];
    [upBtn setTitle:YZMsg(@"提交申请") forState:0];
    upBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [upBtn addTarget:self action:@selector(upBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:upBtn];
    
    
}

-(UIView *)textBackView {
    if (!_textBackView) {
        _textBackView = [[UIView alloc] initWithFrame:CGRectMake(0, titleBack.bottom+5, _window_width, 320)];
        _textBackView.backgroundColor = RGB(245, 245, 245);
        
        _reasonTextView = [[MyTextView alloc] initWithFrame:CGRectMake(10, 15, _window_width-20, _textBackView.height-20)];
        _reasonTextView.backgroundColor = [UIColor clearColor];//RGB(242, 242, 242);
        _reasonTextView.delegate = self;
        _reasonTextView.font = SYS_Font(14);
        _reasonTextView.textColor = UIColor.blackColor;
        _reasonTextView.placeholder = YZMsg(@"请填写详细原因与证据描述,有助于快速解决你的问题");
        _reasonTextView.placeholderColor = UIColor.grayColor;
        
        _wordsNumL = [[UILabel alloc] initWithFrame:CGRectMake(_textBackView.right-60, _textBackView.height-15, 50, 15)];
        _wordsNumL.text = @"0/300";
        _wordsNumL.textColor =  UIColor.grayColor;
        _wordsNumL.font = [UIFont systemFontOfSize:12];
        _wordsNumL.backgroundColor =[UIColor clearColor];
        _wordsNumL.textAlignment = NSTextAlignmentRight;
        
        [_textBackView addSubview:_reasonTextView];
        [_textBackView addSubview:_wordsNumL];
        

    }
    return _textBackView;
}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView*)textView {

    NSString *toBeString = textView.text;
    NSString *lang = [[[UITextInputMode activeInputModes]firstObject] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textView markedTextRange];//获取高亮部分
        UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
        //没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > 300) {
                textView.text = [toBeString substringToIndex:300];
                _wordsNumL.text = [NSString stringWithFormat:@"%lu/300",textView.text.length];
            }else{
                _wordsNumL.text = [NSString stringWithFormat:@"%lu/300",toBeString.length];
            }
        }else{
            //有高亮选择的字符串，则暂不对文字进行统计和限制
        }
    }else{
        // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
        if (toBeString.length > 300) {
            textView.text = [toBeString substringToIndex:300];
            _wordsNumL.text = [NSString stringWithFormat:@"%lu/300",textView.text.length];
        }else{
            _wordsNumL.text = [NSString stringWithFormat:@"%lu/300",toBeString.length];
        }
    }
    
}


-(void)reasonSelClick{
    [self.view endEditing:YES];
    NSString *url = [purl stringByAppendingFormat:@"?service=Seller.getRefundRefuseReason"];
    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                            };
    
    [WYNetworking postWithUrl:@"Seller.getRefundRefuseReason" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            reasonArr =info;
            if (reasonArr.count > 0) {
                resonID =minstr([reasonArr[0] valueForKey:@"id"]) ;
                selReasonStr =minstr([reasonArr[0] valueForKey:@"name"]);
            }
            [self clickChangeLocation];

        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
     }];
}

-(void)clickChangeLocation {
    
    if (!reasonPickBack) {
        reasonPickBack = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height)];
        reasonPickBack.backgroundColor = RGB_COLOR(@"#000000", 0.3);
        [self.view addSubview:reasonPickBack];
        
        UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, _window_height-240, _window_width, 40)];
        titleView.backgroundColor = [UIColor whiteColor];
        [reasonPickBack addSubview:titleView];
        
        [PublicObj lineViewWithFrame:CGRectMake(0, titleView.height-1, _window_width, 1) andColor:RGB(250, 250, 250) andView:titleView];
        
        UIButton *cancleBtn = [UIButton buttonWithType:0];
        cancleBtn.frame = CGRectMake(10, 0, 80, 40);
        cancleBtn.tag = 100;
        [cancleBtn setTitle:YZMsg(@"取消") forState:0];
        [cancleBtn setTitleColor:[UIColor blackColor] forState:0];
        cancleBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [cancleBtn addTarget:self action:@selector(cityCancleOrSure:) forControlEvents:UIControlEventTouchUpInside];
        [titleView addSubview:cancleBtn];
        
        UIButton *sureBtn = [UIButton buttonWithType:0];
        sureBtn.frame = CGRectMake(_window_width-90, 0, 80, 40);
        sureBtn.tag = 101;
        [sureBtn setTitle:YZMsg(@"完成") forState:0];
        [sureBtn setTitleColor:Pink_Cor forState:0];
        sureBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [sureBtn addTarget:self action:@selector(cityCancleOrSure:) forControlEvents:UIControlEventTouchUpInside];
        [titleView addSubview:sureBtn];
        
        UILabel *titlelb = [[UILabel alloc]init];
        titlelb.frame = CGRectMake(_window_width/2-90, 0, 180, 40);
        titlelb.font = [UIFont systemFontOfSize:15];
        titlelb.text = YZMsg(@"拒绝原因");
        titlelb.textColor = [UIColor blackColor];
        [titleView addSubview:titlelb];
        
        reasonPicker = [[UIPickerView alloc]initWithFrame:CGRectMake(0, _window_height-200, _window_width, 200)];
        reasonPicker.backgroundColor = [UIColor whiteColor];
        reasonPicker.delegate = self;
        reasonPicker.dataSource = self;
        reasonPicker.showsSelectionIndicator = YES;
        [reasonPicker selectRow: 0 inComponent: 0 animated: YES];
        [reasonPickBack addSubview:reasonPicker];
    }else{
        reasonPickBack.hidden = NO;
    }
    
}
- (void)cityCancleOrSure:(UIButton *)button{
    if (button.tag == 100) {
        //return;
    }else{
        reasonLb.text =  selReasonStr;
        selResonDic =reasonArr[selRow];
        resonID = minstr([selResonDic valueForKey:@"id"]);
    }
    reasonPickBack.hidden = YES;
    
}
#pragma mark--- Picker Data Source Methods-----
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return reasonArr.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return minstr([reasonArr[row] valueForKey:@"name"]);
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    selReasonStr = minstr([reasonArr[row] valueForKey:@"name"]);
    selRow = row;
    [reasonPicker reloadAllComponents];


}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        pickerLabel.font = [UIFont systemFontOfSize:15];
    }
    if (row == selRow) {
        pickerLabel.textColor = Pink_Cor;
    }
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;

}


#pragma mark--------提交申请----------
-(void)upBtnClick{    
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken],@"orderid":self.orderId,@"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"orderid":self.orderId,
                          @"type":@"0",
                          @"reasonid":resonID,
                          @"refuse_desc":_reasonTextView.text,
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign
                            };
    
    [WYNetworking postWithUrl:@"seller.setGoodsOrderRefund" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            [MBProgressHUD showError:msg];
            if (self.navigationController.viewControllers.count >= 2) {
                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:([self.navigationController.viewControllers count] -3)] animated:YES];

                }
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
     }];
    
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
@end
